package com.mall.mall.cart.interceptor;

import com.mall.common.Vo.MemberResponseVo;
import com.mall.common.constant.AuthServerConstant;
import com.mall.common.constant.CartConstant;
import com.mall.mall.cart.vo.UserInfoTO;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 判断用户的登录状态
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTO> threadLocal = new ThreadLocal<UserInfoTO>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTO userInfoTO = new UserInfoTO();

        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (null != member){
            // 用户登录
            userInfoTO.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies){
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)){
                    userInfoTO.setUserKey(cookie.getValue());
                }
            }
        }

        // 如果没有登录，需要分配一个临时用户
        if (StringUtils.isEmpty(userInfoTO.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTO.setUserKey(uuid);
            userInfoTO.setTempUser(true);
        }
        
        threadLocal.set(userInfoTO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTO userInfoTO = threadLocal.get();

        if (userInfoTO.isTempUser() == true) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTO.getUserKey());
            cookie.setDomain("wtmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

    }
}
